#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include "ui_mainwindow.h"
#include "InheritQObject.h"
#include <QThread>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0) :
        QMainWindow(parent),
        ui(new Ui::MainWindow){

        qDebug()<<"GUI thread = "<<QThread::currentThreadId();

        ui->setupUi(this);

        //创建QThread线程对象以及QObject派生类对象，注意：都不需要设置父类
        m_th = new QThread();
        m_obj = new InheritQObject();

        //改变m_obj的线程依附关系
        m_obj->moveToThread(m_th);

        //释放堆空间资源
        connect(m_th, &QThread::finished, m_obj, &QObject::deleteLater);
        connect(m_th, &QThread::finished, m_th, &QObject::deleteLater);
        //设置野指针为nullptr
        connect(m_th, &QObject::destroyed, this, &MainWindow::SetPtrNullptr);
        connect(m_obj, &QObject::destroyed, this, &MainWindow::SetPtrNullptr);
        //连接其他信号槽，用于触发线程执行槽函数里的任务
        connect(this, &MainWindow::StartTimerSignal, m_obj, &InheritQObject::TimerSlot);
        connect(m_obj, &InheritQObject::ValueChanged, this, &MainWindow::setValue);
        connect(this, &MainWindow::QdebugSignal, m_obj, &InheritQObject::QdebugSlot);
        connect(this, &MainWindow::InitSiganl, m_obj, &InheritQObject::Init);

        //启动线程，线程默认开启事件循环，并且线程正处于事件循环状态
        m_th->start();

        emit InitSiganl();
    }

    ~MainWindow(){
        delete ui;
    }

signals:
    void StartTimerSignal();
    void QdebugSignal();
    void InitSiganl();

private slots:
    //触发线程执行m_obj的计时槽函数
    void on_startBt_clicked(){
        emit StartTimerSignal();
        //m_obj->TimerSlot();
    }

    //退出计时槽函数
    void on_stopBt_clicked(){
        m_obj->StopTimer();
    }

    //检测线程状态
    void on_checkBt_clicked(){
        if(m_th->isRunning()){
            ui->label->setText("Running");
        }else{
            ui->label->setText("Finished");
        }
    }

    void on_SendQdebugSignalBt_clicked(){
        emit QdebugSignal();
    }

    //退出线程
    void on_ExitBt_clicked(){
        m_th->exit(0);
    }

    //强制退出线程
    void on_TerminateBt_clicked(){
        m_th->terminate();
    }

    //消除野指针
    void SetPtrNullptr(QObject *sender){
        if(qobject_cast<QObject*>(m_th) == sender){
            m_th = nullptr;
            qDebug("set m_th = nullptr");
        }

        if(qobject_cast<QObject*>(m_obj) == sender){
            m_obj = nullptr;
            qDebug("set m_obj = nullptr");
        }
    }

    //响应m_obj发出的信号来改变时钟
    void setValue(int i){
            ui->lcdNumber->display(i);
    }

private:
    Ui::MainWindow *ui;
    QThread *m_th;
    InheritQObject *m_obj;
};

#endif // MAINWINDOW_H
